package com.boot.security.server.user.controller;

import com.boot.security.server.annotation.LogAnnotation;
import com.boot.security.server.dto.UserDto;
import com.boot.security.server.page.table.PageTableRequest;
import com.boot.security.server.page.table.PageTableResponse;
import com.boot.security.server.user.dao.UserDao;
import com.boot.security.server.user.model.SysUsers;
import com.boot.security.server.user.service.UserService;
import com.boot.security.server.utils.UserUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

/**
 * 用户相关接口
 * @author Ming
 */
@Api(tags = "用户")

@RestController
@RequestMapping("/users")
public class UserController {

    private static final Logger log = LoggerFactory.getLogger("adminLogger");

    @Autowired
    private UserService userService;
    @Autowired
    private UserDao userDao;

    @LogAnnotation
    @PostMapping
    @ApiOperation(value = "保存用户")
    @PreAuthorize("hasAuthority('sys:user:add')")
    public SysUsers saveUser (@RequestBody UserDto userDto) {
        SysUsers u = userService.getUser(userDto.getUsername());
        if (u != null) {
            throw new IllegalArgumentException(userDto.getUsername() + "已存在");
        }
        return userService.saveUser(userDto);
    }

    @LogAnnotation
    @PutMapping
    @ApiOperation(value = "修改用户")
    @PreAuthorize("hasAuthority('sys:user:add')")
    public SysUsers updateUser (@RequestBody UserDto userDto) {
        return userService.updateUser(userDto);
    }

    @LogAnnotation
    @PostMapping("/{username}/{oldPassword}/{newPassword}")
    @ApiOperation(value = "修改密码")
    @PreAuthorize("hasAuthority('sys:user:password')")
    public void changePassword (@PathVariable String username, @PathVariable String oldPassword, @PathVariable String newPassword) {
        userService.changePassword(username, oldPassword, newPassword);
    }

    @GetMapping()
    @ApiOperation(value = "用户列表")
    @PreAuthorize("hasAuthority('sys:user:query')")
    public PageTableResponse listUsers (PageTableRequest request) {
        return userService.listUsers(request);
    }

    @ApiOperation(value = "当前登录用户")
    @GetMapping("/current")
    public SysUsers currentUser () {
        return UserUtil.getLoginUser();
    }

    @ApiOperation(value = "根据用户id获取用户")
    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('sys:user:query')")
    public SysUsers user (@PathVariable Long id) {
        return userService.getById(id);
    }

    @ApiOperation(value = "根据用户id获取用户")
    @PostMapping("/enDis/{id}")
    @PreAuthorize("hasAuthority('sys:user:query')")
    public SysUsers enDis (@PathVariable Long id) {
        return userService.enDis(id);
    }
}
